package licode.unisop.client.utils;

import licode.unisop.client.api.SopPlatform;
import licode.unisop.client.api.SopPlatformAuth;
import licode.unisop.client.api.SopPlatformMng;
import licode.unisop.client.api.auth.SopUserAuth;
import licode.unisop.client.info.SopPlatHeartInfo;
import licode.unisop.client.info.SopTokenInfo;
import licode.unisop.client.vo.SopAuthUser;
import licode.unisop.client.vo.SopCredential;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * APP认证接口定义
 *
 * @author WR
 */
@Component
public class SopUserAuthUtil {
    @Resource
    private SopUserAuth sopUserAuth;

    @Resource
    private SopPlatformMng platformMng;

    @Resource
    private SopPlatformAuth sopPlatformAuth;

    @Resource
    HttpServletRequest request;

    @Value("${uni-sop.token-name:platform}")
    private String platformName;

    private SopPlatform checkPlatform() {
        String ptName = SopRequestParse.getValue(request, platformName);
        SopPlatform platform = platformMng.getPlatform(ptName);
        if (null == platform || platform.isValid()) {
            /*
             * 平台不可用（在认证中心没有注册）
             */
            throw new SopException(403, "无效平台！");
        }
        return platform;
    }

    private SopTokenInfo getAuthToken() {
        SopPlatform platform = checkPlatform();
        SopTokenInfo authToken = SopRequestParse.getAccessTokenInfo(request);
        authToken.setPlatformId(platform.getId());
        return authToken;
    }

    private SopTokenInfo getRefreshAuthToken() {
        SopPlatform platform = checkPlatform();
        SopTokenInfo authToken = SopRequestParse.getRefreshTokenInfo(request);
        authToken.setRealmId(platform.getRealmId());
        authToken.setPlatformId(platform.getId());
        authToken.setToken(SopRequestParse.getRefreshToken(request));

        return authToken;
    }

    /**
     * 根据Code换取登录信息
     *
     * @return 返回认证后用户信息
     */
    public SopAuthUser token() {
        return sopUserAuth.token(SopRequestParse.getCodeInfo(request));
    }

    /**
     * 对平台连接进行续期
     * @param req 检测参数
     */
    public String renewPlatform(SopPlatHeartInfo req) {
        return sopPlatformAuth.renew(req);
    }

    /**
     * 刷新用户访问令牌
     *
     * @return 返回新的认证信息
     */
    public SopCredential refresh() {
        return sopUserAuth.refresh(getRefreshAuthToken());
    }

    public void logout() {
        sopUserAuth.logout(getAuthToken());
    }

    public void logoutSession() {
        sopUserAuth.logoutSession(getAuthToken());
    }
}
